package java.Servlet;

import Dao.Impl.KnowledgeBaseDAOImpl;
import Dao.Impl.KnowledgeBaseMemberDAOImpl;
import Dao.Impl.UserDAOImpl;
import Dao.KnowledgeBaseDAO;
import Dao.KnowledgeBaseMemberDAO;
import Dao.UserDAO;
import Service.KnowledgeBaseService;
import com.fasterxml.jackson.databind.ObjectMapper;
import entity.KnowledgeBase;
import entity.KnowledgeBaseMember;
import entity.User;
import exception.BusinessException;
import org.json.JSONException;
import org.json.JSONObject;
import req.KnowledgeBaseRequest;
import utils.DBUtil;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.List;

/**
 * @Author Su
 * @Date 2025/4/18 16:11
 * @Version 1.0 （版本号）
 */
@WebServlet("/api/knowledge-base/*")
public class KnowledgeBaseServlet extends HttpServlet {
    private KnowledgeBaseService knowledgeBaseService;
    private ObjectMapper objectMapper;

    @Override
    public void init() throws ServletException {
        try {
            Connection connection = DBUtil.getConnection();
            KnowledgeBaseDAO kbDAO = new KnowledgeBaseDAOImpl(connection);
            KnowledgeBaseMemberDAO memberDAO = new KnowledgeBaseMemberDAOImpl(connection);
            UserDAO userDAO = new UserDAOImpl(connection);
            this.knowledgeBaseService = new KnowledgeBaseService(kbDAO, memberDAO, userDAO);
            this.objectMapper = new ObjectMapper();
        } catch (SQLException e) {
            throw new ServletException("初始化失败", e);
        }
    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp)
            throws ServletException, IOException {
        resp.setContentType("application/json");
        resp.setCharacterEncoding("UTF-8");
        JSONObject responseJson = new JSONObject();
        try {
            String pathInfo = req.getPathInfo();
            HttpSession session = req.getSession(false);
            if (session == null) {
                sendError(resp, 401, "未登录");
                return;
            }

            User user = (User) session.getAttribute("user");
            System.out.println("携带的用户信息" + user);

            if (pathInfo == null || pathInfo.equals("/")) {
                // 获取用户的知识库列表
                List<KnowledgeBase> knowledgeBases = knowledgeBaseService.getUserKnowledgeBases(user.getUserId());
                responseJson.put("code", 200);
                responseJson.put("message", "请求成功");
                responseJson.put("data",knowledgeBases);
            } else if (pathInfo.startsWith("/members/")) {
                // 获取知识库成员列表
                int knowledgeBaseId = Integer.parseInt(pathInfo.substring("/members/".length()));
                List<KnowledgeBaseMember> members = knowledgeBaseService.getKnowledgeBaseMembers(knowledgeBaseId, user.getUserId());
                responseJson.put("code", 200);
                responseJson.put("message", "请求成功");
                responseJson.put("data",members);
            } else {
                // 获取单个知识库信息
                int knowledgeBaseId = Integer.parseInt(pathInfo.substring(1));
                KnowledgeBase kb = knowledgeBaseService.getKnowledgeBase(knowledgeBaseId, user.getUserId());
                responseJson.put("code", 200);
                responseJson.put("message", "请求成功");
                responseJson.put("data",kb);
            }
        } catch (JSONException e) {
            responseJson.put("code", 400);
            responseJson.put("message", "请求参数错误");
            resp.setStatus(HttpServletResponse.SC_BAD_REQUEST);
        } catch (BusinessException e) {
            responseJson.put("code", 405);
            responseJson.put("message", "权限不足");
            resp.setStatus(HttpServletResponse.SC_BAD_REQUEST);
        } catch (SQLException e) {
            responseJson.put("code", 500);
            responseJson.put("message", "系统错误");
            resp.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
            e.printStackTrace();
        } finally {
            resp.getWriter().print(responseJson.toString());
        }
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp)
            throws ServletException, IOException {
        req.setCharacterEncoding("UTF-8");
        resp.setContentType("application/json;charset=UTF-8");
        resp.setCharacterEncoding("UTF-8");
        JSONObject responseJson = new JSONObject();
        try {
            HttpSession session = req.getSession(false);
            if (session == null) {
                sendError(resp, 401, "未登录");
                return;
            }

            User user = (User) session.getAttribute("user");
            // 1、解析请求体
            KnowledgeBaseRequest request = objectMapper.readValue(req.getReader(), KnowledgeBaseRequest.class);

            if (req.getPathInfo() == null || req.getPathInfo().equals("/")) {
                // 创建知识库
                KnowledgeBase kb = knowledgeBaseService.createKnowledgeBase(
                        user.getUserId(),
                        request.getName(),
                        request.getDescription(),
                        request.getAccessLevel()
                );
                responseJson.put("code", 200);
                responseJson.put("message", "添加成功");
            } else if (req.getPathInfo().startsWith("/members/")) {
                // 添加成员
                int knowledgeBaseId = Integer.parseInt(req.getPathInfo().substring("/members/".length()));
                boolean success = knowledgeBaseService.addMember(
                        knowledgeBaseId,
                        user.getUserId(),
                        request.getUserId(),
                        request.getRole()
                );
                responseJson.put("code", 200);
                responseJson.put("message", "添加成功");
            } else {
                responseJson.put("code", 404);
                responseJson.put("message", "无效的路径");
            }
        } catch (JSONException e) {
            responseJson.put("code", 400);
            responseJson.put("message", "请求参数错误");
            resp.setStatus(HttpServletResponse.SC_BAD_REQUEST);
        } catch (BusinessException e) {
            responseJson.put("code", 405);
            responseJson.put("message", "权限不足");
            resp.setStatus(HttpServletResponse.SC_BAD_REQUEST);
        } catch (SQLException e) {
            responseJson.put("code", 500);
            responseJson.put("message", "系统错误");
            resp.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
            e.printStackTrace();
        } finally {
            resp.getWriter().print(responseJson.toString());
        }
    }

    @Override
    protected void doPut(HttpServletRequest req, HttpServletResponse resp)
            throws ServletException, IOException {
        // 1. 统一设置编码和响应类型
        req.setCharacterEncoding("UTF-8");
        resp.setContentType("application/json;charset=UTF-8");
        resp.setCharacterEncoding("UTF-8");

        // 2. 初始化响应JSON对象
        JSONObject responseJson = new JSONObject();

        try {
            // 3. 检查用户登录状态
            HttpSession session = req.getSession(false);
            if (session == null) {
                responseJson.put("code", 401);
                responseJson.put("message", "未登录");
                resp.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
                return;
            }
            User user = (User) session.getAttribute("user");

            // 4. 解析请求体
            KnowledgeBaseRequest request = objectMapper.readValue(
                    req.getReader(),
                    KnowledgeBaseRequest.class
            );

            // 5. 从URL路径获取知识库ID
            String pathInfo = req.getPathInfo();
            if (pathInfo == null || pathInfo.equals("/")) {
                responseJson.put("code", 400);
                responseJson.put("message", "缺少知识库ID");
                resp.setStatus(HttpServletResponse.SC_BAD_REQUEST);
                return;
            }
            int knowledgeBaseId = Integer.parseInt(pathInfo.substring(1));

            // 6. 调用Service更新知识库
            boolean success = knowledgeBaseService.updateKnowledgeBase(
                    knowledgeBaseId,
                    user.getUserId(),
                    request.getName(),
                    request.getDescription(),
                    request.getAccessLevel()
            );

            // 7. 返回响应
            responseJson.put("code", success ? 200 : 400);
            responseJson.put("message", success ? "更新成功" : "更新失败");

        } catch (NumberFormatException e) {
            responseJson.put("code", 400);
            responseJson.put("message", "知识库ID格式错误");
            resp.setStatus(HttpServletResponse.SC_BAD_REQUEST);
        } catch (JSONException e) {
            responseJson.put("code", 400);
            responseJson.put("message", "请求参数格式错误");
            resp.setStatus(HttpServletResponse.SC_BAD_REQUEST);
        } catch (BusinessException e) {
            responseJson.put("code", 403);
            responseJson.put("message", e.getMessage());
            resp.setStatus(HttpServletResponse.SC_FORBIDDEN);
        } catch (SQLException e) {
            responseJson.put("code", 500);
            responseJson.put("message", "系统内部错误");
            resp.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
            e.printStackTrace();
        } finally {
            resp.getWriter().print(responseJson.toString());
        }
    }

    @Override
    protected void doDelete(HttpServletRequest req, HttpServletResponse resp)
            throws ServletException, IOException {
        // 1. 统一设置编码和响应类型
        resp.setContentType("application/json;charset=UTF-8");
        resp.setCharacterEncoding("UTF-8");

        // 2. 初始化响应JSON对象
        JSONObject responseJson = new JSONObject();

        try {
            // 3. 检查用户登录状态
            HttpSession session = req.getSession(false);
            if (session == null) {
                responseJson.put("code", 401);
                responseJson.put("message", "未登录");
                resp.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
                return;
            }
            User user = (User) session.getAttribute("user");

            // 4. 解析URL路径
            String pathInfo = req.getPathInfo();
            if (pathInfo == null || pathInfo.equals("/")) {
                responseJson.put("code", 400);
                responseJson.put("message", "缺少操作目标ID");
                resp.setStatus(HttpServletResponse.SC_BAD_REQUEST);
                resp.getWriter().print(responseJson.toString());
                return;
            }

            String[] pathParts = pathInfo.split("/");

            if (pathParts.length == 2) {
                // 5.1 删除知识库
                int knowledgeBaseId = Integer.parseInt(pathParts[1]);
                boolean success = knowledgeBaseService.deleteKnowledgeBase(
                        knowledgeBaseId,
                        user.getUserId()
                );

                responseJson.put("code", success ? 200 : 400);
                responseJson.put("message", success ? "删除成功" : "删除失败");

            } else if (pathParts.length == 4 && pathParts[2].equals("members")) {
                // 5.2 移除成员
                int knowledgeBaseId = Integer.parseInt(pathParts[1]);
                int memberId = Integer.parseInt(pathParts[3]);

                // 禁止移除自己
                if (memberId == user.getUserId()) {
                    responseJson.put("code", 400);
                    responseJson.put("message", "不能移除自己");
                    resp.setStatus(HttpServletResponse.SC_BAD_REQUEST);
                    return;
                }

                boolean success = knowledgeBaseService.removeMember(
                        knowledgeBaseId,
                        user.getUserId(),
                        memberId
                );

                responseJson.put("code", success ? 200 : 400);
                responseJson.put("message", success ? "成员移除成功" : "成员移除失败");

            } else {
                // 5.3 无效路径
                responseJson.put("code", 404);
                responseJson.put("message", "无效的API路径");
                resp.setStatus(HttpServletResponse.SC_NOT_FOUND);
            }

        } catch (NumberFormatException e) {
            responseJson.put("code", 400);
            responseJson.put("message", "ID格式错误");
            resp.setStatus(HttpServletResponse.SC_BAD_REQUEST);
        } catch (BusinessException e) {
            responseJson.put("code", 403);
            responseJson.put("message", e.getMessage());
            resp.setStatus(HttpServletResponse.SC_FORBIDDEN);
        } catch (SQLException e) {
            responseJson.put("code", 500);
            responseJson.put("message", "系统内部错误");
            resp.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
            e.printStackTrace();
        } finally {
            resp.getWriter().print(responseJson.toString());
        }
    }

    private void sendError(HttpServletResponse resp, int code, String message) throws IOException {
        resp.setStatus(code);
        resp.getWriter().write("{\"error\":\"" + message + "\"}");
    }

}